package com.jinlejia.erp.ui.customer;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.FragmentDetailCustomerBinding;
import com.jinlejia.erp.utils.CallUtils;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;

/**
 * 客源详情
 */
public class DetailCustomerFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private View view;
    private String csCode;
    private String type;
    private String phoneNO;
    private ArrayList<Map<String, Object>> sourceData = new ArrayList<>();
    private String source1, source2;

    public static DetailCustomerFragment newInstance(String code, String type) {
        DetailCustomerFragment fragment = new DetailCustomerFragment();
        Bundle args = new Bundle();
        args.putString("code", code);
        args.putString("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            csCode = getArguments().getString("code");
            type = getArguments().getString("type");
        }
    }
    private FragmentDetailCustomerBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_detail_customer, null);
            binding = DataBindingUtil.bind(view);
            binding.setEvent(this);
            initView();
//            getData();
            getSource();
        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        binding = DataBindingUtil.bind(view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void initView() {
        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refreshLayout.setOnRefreshListener(this);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlLink:
                if (null != binding.telBtn.getTag()) {
                    phoneNO = binding.telBtn.getTag().toString();
                    CallUtils.CallTel(getActivity(),phoneNO);
                } else {
                    CustomToast.showToast(getActivity(), "无联系电话", 1500);
                }
                break;
            case R.id.btAllFollow:
                Intent intent = new Intent(getActivity(), CustomerFllowActivity.class);
                intent.putExtra("code", csCode);
                intent.putExtra("type", type);
                startActivity(intent);
                break;
        }
    }

    private void getData() {
        String url;
        if (type.equals("rent")) {
            url = ApiConfig.RENT_CUSTOMER_DETAIL;
        } else {
            url = ApiConfig.SALE_CUSTOMER_DETAIL;
        }
        OkHttpUtils.get()
                .url(url.concat(csCode))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                        if (DataFilter.filter(getActivity(), response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            EventBus.getDefault().post(data, "TAG_CUSTOMER_DATA");

                            if (type.equals("rent")) {
                                binding.customerType.setText("求租");
                            } else {
                                binding.customerType.setText("求购");
                            }
                            binding.customerName.setText(data.getString("name"));
                            if (data.getIntValue("sex") == 0) {
                                binding.customerGender.setText("女士");
                                binding.RIVImg.setImageResource(R.mipmap.ic_women);
                            } else {
                                binding.customerGender.setText("先生");
                                binding.RIVImg.setImageResource(R.mipmap.ic_man);
                            }
                            //意愿等级
                            binding.ratingbar.setRating(data.getIntValue("level"));
                            //标签
                            if (data.containsKey("tags")) {
                                JSONArray tagArr = JSON.parseArray(data.getString("tags"));
                                binding.tagCload.setTags(JSON.parseArray(tagArr.toJSONString(), String.class));
                            }
                            //客源编号
                            binding.customerNo.setText(data.getString("csCode"));
                            //委托时间
                            if (data.containsKey("entrustTime"))
                                binding.delegateTime.setText(DateUtil.getTime(data.get("entrustTime").toString(), "yyyy-MM-dd HH:mm"));
                            //委托来源
                            if (data.containsKey("sourceType") && !TextUtils.isEmpty(data.getString("sourceType")))
                                source1 = data.getString("sourceType");
                            if (data.containsKey("source") && !TextUtils.isEmpty(data.getString("source")))
                                source2 = data.getString("source");
                            if (sourceData.size() > 0) {
                                binding.delegateFrom.setText(getSource1(source1) + "    " + data.getString("source"));
                            }
                            //归属人
                            binding.belongTo.setText( data.getString("belongUserName") +" | "+ data.getString("belongDept") );
                            //意愿1
                            if (data.containsKey("customerOrderList") && null != data.getJSONArray("customerOrderList")) {
                                JSONArray array = data.getJSONArray("customerOrderList");
                                JSONObject object = (JSONObject) array.get(0);
                                //位置
                                binding.hLocation.setText(object.getString("orderCounty") + "-" + object.getString("orderArea"));
                                //面积
                                binding.hArea.setText(object.get("orderSquareMin") + "-" + object.get("orderSquareMax") + "㎡");
                                //价格
                                if (type.equals("rent")) {
                                    binding.hPrice.setText(object.get("orderPriceMin") + "-" + object.get("orderPriceMax") + "元");
                                } else {
                                    binding.hPrice.setText(object.get("orderPriceMin") + "-" + object.get("orderPriceMax") + "万");
                                }
                                //楼层
//                            hFloor.setText(object.get(""));
                                //居室
                                binding.hRooms.setText(object.get("orderHouseType").toString().replaceAll(";", "居;").concat("居"));
                                //付款方式
                                binding.payWay.setText(object.getString("payType"));
                                //朝向
                                binding.face.setText(object.getString("orderFace"));
                                //装修
                                binding.zhuangxiu.setText(object.getString("orderFit"));
                                //需求备注
                                binding.demandNote.setText(object.getString("needRemark"));
                                if (TextUtils.isEmpty(object.getString("orderCounty")) || TextUtils.isEmpty(object.getString("orderArea"))){
                                    binding.intention.setVisibility(View.GONE);
                                }else {
                                    binding.intention.setVisibility(View.VISIBLE);
                                }
                                if (array.size() > 1) {
                                    JSONObject object2 = (JSONObject) array.get(1);
                                    if (object2.containsKey("id")) {
                                        binding.intention2.setVisibility(View.VISIBLE);
                                        //位置
                                        binding.hLocation2.setText(object2.getString("orderCounty") + "-" + object2.getString("orderArea"));
                                        //面积
                                        binding.hArea2.setText(object2.get("orderSquareMin") + "-" + object2.get("orderSquareMax") + "㎡");
                                        //价格
                                        if (type.equals("rent")) {
                                            binding.hPrice2.setText(object2.get("orderPriceMin") + "-" + object2.get("orderPriceMax") + "元");
                                        } else {
                                            binding.hPrice2.setText(object2.get("orderPriceMin") + "-" + object2.get("orderPriceMax") + "万");
                                        }
                                        //楼层
//                            hFloor2setText(object2.get(""));
                                        //居室
                                        binding.hRooms2.setText(object2.getString("orderHouseType").replaceAll(";", "居;").concat("居"));
                                        //付款方式
                                        binding.payWay2.setText(object2.getString("payType"));
                                        //朝向
                                        binding.face2.setText(object2.getString("orderFace"));
                                        //装修
                                        binding.zhuangxiu2.setText(object2.getString("orderFit"));
                                        //需求备注2
                                        binding.demandNote2.setText(object2.getString("needRemark"));

                                        if (TextUtils.isEmpty(object2.getString("orderCounty")) || TextUtils.isEmpty(object2.getString("orderArea"))){
                                            binding.intention2.setVisibility(View.GONE);
                                        }else {
                                            binding.intention2.setVisibility(View.VISIBLE);
                                        }
                                    }
                                } else {
                                    binding.intention2.setVisibility(View.GONE);
                                }
                            }
                            if (binding.intention.getVisibility()==View.GONE && binding.intention2.getVisibility()==View.GONE){
                                binding.lineView.setVisibility(View.GONE);
                            }
                            //联系人
                            if (data.containsKey("customerContact") && !TextUtils.isEmpty(data.getJSONObject("customerContact").getString("name"))) {
                                binding.llContact.setVisibility(View.VISIBLE);
                                JSONObject customerContact = data.getJSONObject("customerContact");
                                binding.linkmanName.setText(customerContact.getString("name"));
                                if (customerContact.getIntValue("sex") == 0) {
                                    binding.relation.setText("女士");
                                } else {
                                    binding.relation.setText("先生");
                                }
                                binding.telBtn.setTag(customerContact.get("tel"));
                            } else {
                                binding.llContact.setVisibility(View.GONE);
                            }
                            //最新跟进
                            if (data.containsKey("customerFollow")) {
                                binding.llFollow.setVisibility(View.VISIBLE);
                                JSONObject customerFollow = data.getJSONObject("customerFollow");
                                if (customerFollow.containsKey("followTime"))
                                    binding.followTime.setText(DateUtil.getTime(customerFollow.getString("followTime"), "yyyy-MM-dd HH:mm"));
                                binding.followBroker.setText(customerFollow.getString("followUserName") + "    " + customerFollow.getString("dept"));
                                binding.followType.setText(customerFollow.getString("followType"));
                                binding.followMessage.setText(customerFollow.getString("followContent"));
                            } else {
                                binding.llFollow.setVisibility(View.GONE);
                            }


                        }
                    }
                });
    }

    /**
     * 获取委托来源列表
     */
    private void getSource() {
        OkHttpUtils.get()
                .url(ApiConfig.SOURCE_CUSTOMER)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getContext(), response)) {
                            if (null != response.get("data")) {
                                JSONArray data = JSON.parseArray(response.get("data").toString());
                                sourceData = JSON.parseObject(data.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                                if (!TextUtils.isEmpty(source1)) {
                                    binding.delegateFrom.setText(getSource1(source1) + "    " + source2);
                                }
                            }
                        }
                    }
                });
    }

    private String getSource1(String str) {
        for (Map<String, Object> map : sourceData) {
            if (map.get("valuel").toString().equals(str)) {
                return map.get("valueName").toString();
            }
        }
        return "";
    }

    @Override
    public void onRefresh() {
        getData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
